module app.controller.admin.ProfileController;

import std.json;
import hunt.framework;
import app.response.ResultMsg;
import app.utils.RespCodeEnun;
import app.repository.ProfileRepository;
import app.model.Profile;
import app.middleware.CheckIdValidity;

class ProfileController : Controller
{
    mixin MakeController;

    /**
    * 获取个人信息
    */
    @Middleware(CheckIdValidity.stringof)  // id参数检查中间件
    @Action Response detail(long id)
    {
        ResultMsg resultMsg = new ResultMsg;
        ProfileRepository profileRepository = new ProfileRepository();
        try
        {
            Profile profile = profileRepository.findById(id);

            JSONValue item;
            item["id"] = profile.id;
            item["avatar"] = profile.avatar;
            item["slogan"] = profile.slogan;
            item["name"] = profile.name;
            item["domain"] = profile.domain;
            item["gitee"] = profile.gitee;
            item["desc"] = profile.desc;
            item["notice"] = profile.notice;
            item["qqchat"] = profile.qqchat;
            item["wechat"] = profile.wechat;
            item["bili"] = profile.bili;
            item["email"] = profile.email;

            resultMsg.code = RespCodeEnun.SUCCESS;
            resultMsg.msg = "success";
            resultMsg.data["data"] = item;
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            resultMsg.code = RespCodeEnun.ERROR;
            resultMsg.msg = "系统错误";
        }

        return new JsonResponse(resultMsg);
    }

    /**
    * 更新
    */
    @Middleware(CheckIdValidity.stringof)  // id参数检查中间件
    @Action Response update(long id)
    {
        ResultMsg resultMsg = new ResultMsg;
        ProfileRepository profileRepository = new ProfileRepository();

        // 接收提交的json数据
        JSONValue updateJson = request.json();
        try
        {
            Profile profile = profileRepository.findById(id);
            profile.name = updateJson["name"].str;
            profile.avatar = updateJson["avatar"].str;
            profile.slogan = updateJson["slogan"].str;
            profile.domain = updateJson["domain"].str;
            profile.gitee = updateJson["gitee"].str;
            profile.desc = updateJson["desc"].str;
            profile.notice = updateJson["notice"].str;
            profile.qqchat = updateJson["qqchat"].str;
            profile.wechat = updateJson["wechat"].str;
            profile.bili = updateJson["bili"].str;
            profile.email = updateJson["email"].str;

            // 更新
            profileRepository.save(profile);
            resultMsg.code = RespCodeEnun.SUCCESS;
            resultMsg.msg = "success";
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            resultMsg.code = RespCodeEnun.ERROR;
            resultMsg.msg = "系统错误";
        }
        return new JsonResponse(resultMsg);
    }
}
